<template>
  <div class="info-box" v-if="requirementData">
    <!-- 需求标题 -->
    <div class="info-title">
      <p class="info-status"
        :style="{
          color:
            requirementData.itemRequirementIsEnter <= 3 &&
            requirementData.requirementBossName == ''
              ? enterStatus(requirementData.itemRequirementIsEnter).bgColor
              : fatherStatus(requirementData.requirmentFatherStatus).bgColor,
        }"
      >
        {{
          requirementData.itemRequirementIsEnter <= 3 &&
          requirementData.requirementBossName == ""
            ? enterStatus(requirementData.itemRequirementIsEnter).text
            : fatherStatus(requirementData.requirmentFatherStatus).text
        }} - 
      </p>
      <p class="info-title-text">
        <el-tooltip :content="requirementData.requirementName" placement="top" effect="light">
          <el-text truncated style="color: black;">{{ requirementData.requirementName }}</el-text>
        </el-tooltip>
      </p>
    </div>
    <!-- 相关人员信息 -->
    <div class="info-user">
      <div class="info-user-colum">
        <div class="info-user-one">
          <p
            class="info-user-text-box"
            v-if="requirementData.requirementCreateName"
          >
            <span class="info-user-title">创建人：</span
            >{{ requirementData.requirementCreateName }}
          </p>
          <p
            class="info-user-text-box"
            v-if="requirementData.requirementAuditName"
          >
            <span class="info-user-title">审核人：</span
            >{{ requirementData.requirementAuditName }}
          </p>
        </div>
        <div class="info-user-one">
          <p
            class="info-user-text-box"
            v-if="requirementData.requirementBossName"
          >
            <span class="info-user-title">技术负责人：</span
            >{{ requirementData.requirementBossName }}
          </p>
        </div>
        <div class="info-user-one">
          <p
            class="info-user-text-box"
            v-if="requirementData.contactTestBossName"
          >
            <span class="info-user-title">测试负责人：</span
            >{{ requirementData.contactTestBossName }}
          </p>
        </div>
      </div>
      <div class="info-user-colum">
        <div class="info-user-one">
          <p class="info-user-text-box">
            <span class="info-user-title">创建时间：</span
            >{{ tableTimeDate(requirementData.createAt) }}
          </p>
        </div>
        <div class="info-user-one">
          <p
            class="info-user-text-box"
            v-if="requirementData.requirementRelevances"
          >
            <span class="info-user-title">研发人员：</span
            >{{ requirementData.requirementRelevances }}
          </p>
        </div>
        <div class="info-user-one">
          <p
            class="info-user-text-box"
            v-if="
              requirementData.contactTestNames !== '' &&
              requirementData.contactTestNames !== '|'
            "
          >
            <span class="info-user-title">参与测试人员：</span
            >{{ requirementData.contactTestNames }}
          </p>
        </div>
      </div>
    </div>

    <!-- 需求简述 -->
    <div class="info-content-box">
      <p class="info-content-title">
        <span class="info-user-title">需求简述：</span>
      </p>
      <el-card class="el-card-content">
        <div
          class="info-content"
          v-html="requirementData.requirementContent"
        ></div>
      </el-card>
    </div>

    <!-- 需求草稿文档下载 -->
    <div class="info-file-box" v-if="draftFiles.length !== 0">
      <p class="info-content-title">
        <span class="info-user-title">需求草稿：</span>
      </p>
      <ul class="info-file-ul">
        <li
          class="info-file-item"
          v-for="(item, index) in draftFiles"
          :key="index"
          @click="handleDownloadFile(item, baseUrl)"
        >
          <el-icon :size="12">
            <Document /> </el-icon
          >{{ item.name }}
        </li>
      </ul>
    </div>

    <!-- 分配参与人员 -->
    <el-card
      class="el-card-childs"
      v-if="
        requirementData !== undefined &&
        requirementData.itemRequirementChilds.length !== 0
      "
    >
      <!--  <p class="title el-card-childs-title">参与人：<span style="font-weight: normal;"
            v-for="(item, index) in requirementData.itemRequirementChilds" :key="index">{{ item.userName
            }}&nbsp;&nbsp;</span></p>
            <ul class="el-card-childs-ul">
                <li class="el-card-childs-item" v-for="(item, index) in requirementData.itemRequirementChilds" :key="index">
                    <p class="el-card-childs-item-name">{{ item.userName }}</p>
                    <p class="el-card-childs-item-time">{{ tableTimeDate(item.guessTime) }}</p>
                    <p class="el-card-childs-item-job">
                        前完成：<span style="background-color: #ddd;padding: 0 5px;">{{ item.processJob }}</span>，
                    </p>
                    <p class="el-card-childs-item-process">
                        耗时：<span style="background-color: #ddd;padding: 0 5px;">{{ item.guessProcess }}</span>小时
                    </p>
                    <p class="el-card-childs-item-status">
                        {{ item.isTs == 2 && item.requirmentChildStatus < 5 ? "等待提测" : fatherStatus(item.requirmentChildStatus).text }}
                    </p>
                    <div v-if="item.itemRequirementWorldDetailed !== ''">
                        <p class="info-content-title">
                            详细设计：
                            <span style="color: blue;cursor: pointer;"
                            @click="handleDownloadFile(handleFileName(item.itemRequirementWorldDetailed), baseUrl)">
                            <el-icon :size="12">
                                    <Document />
                                </el-icon>{{ handleFileName(item.itemRequirementWorldDetailed).name }}
                            </span>
                        </p>
                    </div>
                </li>
            </ul> -->

      <!-- 任务列表 -->
      <p class="info-content-title">
        <span class="info-user-title">已分配任务：</span>
      </p>
      <el-table
        :data="tableData"
        style="width: 100%"
        align="center"
        stripe
        border
        :default-expand-all="true"
        row-key="ID"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div
              style="padding: 20px; background-color: rgb(243.9, 244.2, 244.8)"
            >
              <div class="table-inline">
                <p v-if="props.row.itemRequirementWorldDetailed !== ''">
                  附件：
                  <span
                    style="color: blue; cursor: pointer"
                    @click="
                      handleDownloadFile(
                        handleFileName(props.row.itemRequirementWorldDetailed),
                        baseUrl
                      )
                    "
                  >
                    <el-icon :size="12">
                      <Document /> </el-icon
                    >{{
                      handleFileName(props.row.itemRequirementWorldDetailed)
                        .name
                    }}
                  </span>
                </p>
                <p v-if="props.row.isTs == 1 && props.row.testUserNames !== ''">
                  <span>测试人员：{{ props.row.testUserNames }}</span>
                </p>
              </div>
              <el-table
                v-if="props.row.itemRequirementBranchTests.length !== 0"
                :data="props.row.itemRequirementBranchTests"
              >
                <el-table-column label="测试人员" prop="testName" />
                <el-table-column label="测试状态" prop="testStatus">
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      plain
                      :disabled="row.testStatus !== 2"
                      @click="hanldeUpdateTestStatus(row.ID)"
                      >{{ testStatus(row.testStatus).text }}</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="归属人"
          prop="userName"
          width="100px"
          align="center"
        />
        <el-table-column
          label="任务内容"
          prop="processJob"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="预计完成时间"
          prop="guessTime"
          align="center"
          width="120px"
        >
          <template #="{ row }">
            <span>{{ tableTimeDate(row.guessTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="耗时评估(h)"
          prop="guessProcess"
          align="center"
          width="100px"
        />
        <el-table-column
          label="任务难度评分"
          prop="processJobNum"
          align="center"
          width="120px"
        />
        <el-table-column
          label="任务进度"
          prop="requirmentChildStatus"
          align="center"
          width="100px"
        >
            <template #="{ row }">
                <span style="color: red">{{
                row.isTs == 2 && row.requirmentChildStatus < 5
                    ? "等待提测"
                    : row.requirmentChildStatus == 5
                    ? testStatus(row.submitTestNext).text
                    : fatherStatus(row.requirmentChildStatus).text
                }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px" v-if="isUserAuthId == '111' || isUserAuthId == '555'">
          <template #="{row}">
            <el-button type="danger" size="small" @click="handleDelChildUser(row)" :disabled="userName !== row.avgUserName">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  defineProps,
  watch,
  onMounted,
  onBeforeUnmount,
  onUnmounted,
} from "vue";
import {
  PostRequirement, GetUpdateMySubmitByRequirementStatus, PostAvgDeleteRequirement,
} from "@/api/newDemands/index";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
import {
  tableTimeDate,
  enterStatus,
  fatherStatus,
  handleFileName,
  handleDownloadFile,
  testStatus,
} from "@/utils/utils";

const props = defineProps({
  isRequirementID: {
    type: Number,
    required: true,
  },
  clearData: {
    type: Boolean,
    required: true,
  },
});
const ew =ref();

let userInfoStore = useUserStore();
const userName = ref<any>("");// 当前用户
const isID = ref<any>(props.isRequirementID);
const requirementData = ref<any>(null); //该需求所有数据
const draftFiles = ref<any>([]); //该需求所有的需求草稿地址
// const baseUrl = ref(import.meta.env.VITE_SERVE); //服务器地址
const baseUrl = ref(""); //服务器地址
const tableData = ref<any>([]); // 任务列表
const deleteRequirementForm = ref<any>({
  itemRequirementId: null,
  devs: [],
  ts: []
});// 删除分配人员提交数据
const isUserAuthId = ref<any>();//当前用户

watch(
  () => props.clearData,
  (newClearData) => {
    if (newClearData) {
      requirementData.value = null;
      isID.value = null;
      console.log(
        "监听子组件中的值",
        "newClearData:",
        newClearData,
        "requirementData:",
        requirementData.value,
        "isID:",
        isID.value
      );
    }
  }
);

watch(
  () => props.isRequirementID,
  async (newIsId) => {
    isID.value = newIsId;
    console.log("监听子组件中接收值：", isID.value);
    requirementData.value = null;
    draftFiles.value = [];
    await getRequirementData();
  }
);

// TODO 查询一个需求
const getRequirementData = async () => {
  console.log(isID.value);
  isUserAuthId.value = localStorage.getItem("authorityId");
  console.log(isUserAuthId.value);
  userName.value = userInfoStore.$state.userInfo.nickName;
  console.log("userName:", userName.value);
  const { data } = await PostRequirement({
    id: isID.value,
  });

  if (data.code === 200) {
    requirementData.value = data.data;
    console.log("查询一个需求：", requirementData.value);

    // 已分配研发/测试任务数据处理
    if (data.data.itemRequirementChilds.length !== 0) {
      tableData.value = data.data.itemRequirementChilds;
      console.log("任务列表：", tableData.value);
    }

    // 需求草稿地址
    if (
      data.data.itemRequirementWorldDraft !== "" ||
      data.data.itemRequirementWorldDraft.includes("|")
    ) {
      if (data.data.itemRequirementWorldDraft.includes("|")) {
        draftFiles.value = data.data.itemRequirementWorldDraft
          .split("|")
          .map((url: string) => {
            return handleFileName(url);
          });
      } else {
        draftFiles.value[0] = handleFileName(
          data.data.itemRequirementWorldDraft
        );
      }
      console.log("需求草稿地址", draftFiles.value);
    }
  } else {
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  }
};

// TODO 待测试-测试中
const hanldeUpdateTestStatus = async (id: number) => {
  const { data } = await GetUpdateMySubmitByRequirementStatus(id);
  if (data.code === 200) {
    await getRequirementData();
    return;
  } else {
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  }
};

// TODO 删除已分配人员
const handleDelChildUser = async (val: any) => {
  console.log("删除人员：", val);

  await ElMessageBox.confirm(`确认删除${val.userName}吗？`, "操作", {
    type: "warning",
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    closeOnClickModal: false,
    closeOnPressEscape: false,
  }).then (async () => {
    if (val.isTs == 1) {
      deleteRequirementForm.value = {
        itemRequirementId: val.itemRequirementId,
        devs: [{
          userUUID: val.userUUID,
          userName: val.userName
        }],
        ts: []
      }
    } else {
      deleteRequirementForm.value = {
        itemRequirementId: val.itemRequirementId,
        devs: [],
        ts: [{
          userUUID: val.userUUID,
          userName: val.userName
        }]
      }
    };
    console.log("删除人员：", deleteRequirementForm.value);
  
    const {data} = await PostAvgDeleteRequirement(deleteRequirementForm.value);
    if (data.code === 200) {
        await getRequirementData();
        ElMessage.success(data.msg);
          deleteRequirementForm.value = {
          itemRequirementId: null,
          devs: [],
          ts: []
        };

      return;
    } else {
      ElMessage.error(data.msg);
      return;
    }
  }).catch(() => {
    deleteRequirementForm.value = {
      itemRequirementId: null,
      devs: [],
      ts: []
    };
    return;
  })
};

// const expandedRowKeys = ref<number[]>([]);

// 方法
/* const handleExpandChange = (row: any, expanded:any) => {
  const rowIndex = expandedRowKeys.value.indexOf(row.ID);
  if (expanded) {
    if (rowIndex === -1) {
      expandedRowKeys.value.push(row.ID);
    }
  } else {
    if (rowIndex !== -1) {
      expandedRowKeys.value.splice(rowIndex, 1);
    }
  }
}; */

// 判断某一行是否可以展开
/* const judgeRowCanBeExpand = ({ row:any }) => {
    console.log("row:", row);
  return row.itemRequirementBranchTests?.length > 0;
}; */

onMounted(async () => {
  await getRequirementData();
  // 初始化展开的行
  // expandedRowKeys.value = tableData.value
  //   .filter((row: any) => judgeRowCanBeExpand({ row }))
  //   .map((row: any) => row.ID);
});
</script>
<style lang="scss" scoped>
.info-box {
  width: 100%;
  min-height: 200px;
  max-height: 600px;
  overflow-y: auto;

  .info-title {
    width: 100%;
    color: #000;
    background-color: rgb(243.9, 244.2, 244.8);
    font-size: 1rem;
    font-family: Arial, Helvetica, sans-serif;
    padding: 10px;
    margin-bottom: 10px;
    font-weight: bolder;
    border-bottom: 1px solid rgb(177.3, 179.4, 183.6);
    display: flex;
    flex-direction: row;
    .info-status {
      max-width: 100px;
    };
    .info-title-text {
      width: calc(100% - 100px);
      font-size: 1rem;
    }
  }

  .info-user {
    width: 100%;
    line-height: 1rem;
    color: #000;
    background-color: rgb(243.9, 244.2, 244.8);
    display: flex;
    margin-bottom: 10px;
    flex-direction: row;

    .info-user-colum {
      width: 50%;
      display: flex;
      justify-content: flex-start;
      flex-direction: column;

      .info-user-text-box {
        padding-right: 40px;
        padding-left: 20px;
      }

      .info-user-one {
        display: flex;
        justify-content: start;
        flex-direction: row;
      }

      p {
        padding: 5px 10px;
      }
    }
  }

  .info-user-title {
    color: #000;
    font-weight: bold;
  }

  // 需求简述
  .info-content-box {
    width: 100%;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    flex-direction: row;

    .info-content-title {
      width: 90px;
      padding-left: 20px;
      // background-color: red;
    }

    .el-card-content {
      width: calc(100% - 90px);
      // height: 200px;
      // min-height: 200px;
      max-height: 400px;
      overflow-y: auto;
    }
  }

  // 需求草稿
  .info-file-box {
    width: 100%;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    padding: 5px 20px;
    background-color: rgb(243.9, 244.2, 244.8);

    .info-content-title {
      width: 70px;
    }

    .info-file-ul {
      width: calc(100% - 70px);
      text-align: left;
      display: flex;
      flex-direction: row;

      .info-file-item {
        width: 100px;
        color: blue;
        margin-right: 10px;
        cursor: pointer;
      }
    }
  }

  .title {
    font-weight: bolder;
  }

  .el-card-childs-title {
    padding-bottom: 10px;
  }

  .el-card-childs-ul {
    width: 100%;
    height: 100%;
    .el-card-childs-item {
      width: 100%;
      // min-height: 40px;
      padding: 5px 10px;
      // line-height: 40px;
      margin-bottom: 2px;
      display: flex;
      // flex-direction: column;
      justify-content: flex-start;
      flex-direction: row;
      font-size: 12px;
      background-color: rgb(243.9, 244.2, 244.8);
      // .el-card-child-one {
      //     width: 100%;
      //     display: flex;
      //     flex-direction: row;
      // }
      // .el-card-child-two {
      //     padding-top: 5px;
      // }

      .el-card-childs-item-name {
        width: 40px;
      }

      .el-card-childs-item-time {
        margin: 0 10px;
      }

      .el-card-childs-item-status {
        margin-left: 10px;
        margin-right: 10px;
        color: red;
      }
    }
  }

  // 任务表格
  .table-inline {
    width: 100%;
    padding-bottom: 10px;
    display: flex;
    justify-content: flex-start;
    p {
      padding-right: 20px;
    }
  }
}
</style>
